package com.zx.framework.plat.module.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zx.framework.core.pagination.Pagination;
import com.zx.framework.db.KeyValue;
import com.zx.framework.plat.PlatController;
import com.zx.framework.plat.module.ModuleUtil;
import com.zx.framework.plat.module.po.Module;
import com.zx.framework.plat.user.po.User;
import com.zx.framework.plat.user.vo.UserVo;
import com.zx.framework.web.exception.AjaxException;
import com.zx.framework.web.exception.UIException;
/**
 * 操作菜单的controller
 * @author stylewolf
 *
 */
@Controller
@RequestMapping("/module")
public class ModuleController extends PlatController {

    private static final Logger LOGGER = Logger.getLogger(ModuleController.class);

    @InitBinder("module")
    public void moduleBinder(WebDataBinder binder) throws Exception {
        binder.setFieldDefaultPrefix("module.");
    }
    
    /**
     * 获取登录用户的菜单信息
     * @param platform 平台种类
     * @param project 所属项目
     * @return
     */
    @RequestMapping("/query/login")
    @ResponseBody
    public Object queryLoginUserModule(String platform,String ... project){
    	
    	try {
			User login = getSessionKeyObject(User.class);
			List<Module> list = moduleService.findUserModules(login.getId(), platform, project);
			login.setPassword("******");
			return clientMap().success().message("获取成功！").datas(list).put("login",login).getMap(); 
		} 
    	catch (Exception e) {
			LOGGER.error("",e);
			throw new AjaxException(e.getMessage());
		}
    }
    /**
     * 获取当前菜单的布局文件
     * @param id
     * @return
     */
    @RequestMapping("/layout/{id}")
    @ResponseBody
    public String loadLayout(@PathVariable("id") String id){
    	User login = getSessionKeyObject(User.class);
    	if(moduleService.hasModule(login.getId(), id)){
    		Module module = moduleService.findModuleById(id);
    		List<KeyValue> keyValues = new ArrayList<KeyValue>();
    		keyValues.add(new KeyValue("owner", module.getId()));
    		keyValues.add(new KeyValue("status", OBJECT_USED));
    		//获取子菜单
    		List<Module> modules = moduleService.findByPropertys(keyValues, "layer");
    		return ModuleUtil.readLayout(module,modules);
    	}else{
    		throw new AjaxException("您没用此菜单的操作权限");
    	}
    }
    /**
     * 根据ID获取菜单信息
     * @param id
     * @return
     */
    @RequestMapping("/query/id/{id}")
    public Object queryModuleById(@PathVariable("id") String id){
    	try {
			Module module = moduleService.findModuleById(id);
			if(module == null){
				throw new AjaxException("菜单信息不存在！");
			}
			return clientMap().success().message("获取成功！").put("module",module);
		}catch (AjaxException e) {
			throw e;
		}catch (Exception e) {
			LOGGER.error("",e);
			throw new AjaxException("获取菜单信息失败！");
		}
    }

    /**
     * 分页查询方法
     * @param module   查询模板
     * @param pagination    分页
     * @return              分页模板路径
     */
    @RequestMapping("/page")
    public String query( Module module, Pagination<Module> pagination,Model model) {
    	try{
			model.addAttribute("module", module);
        	model.addAttribute("pagination", moduleService.pageQuery(module, pagination.getPage(), pagination.getRows()));
		}catch (Exception e) {
			throw new UIException("获取菜单列表信息失败！");
		}
        return "module/list";
    }
    /**
     * ajax返回json的列表数据
     * @param module
     * @param pagination
     * @param model
     * @return 返回列表的json
     */
    @RequestMapping("/ajax/page")
    public Object ajaxQuery( Module module, Pagination<Module> pagination,Model model) {
    	try{
        	model.addAttribute("pagination", moduleService.pageQuery(module, pagination.getPage(), pagination.getRows()));
        	return clientMap().success().message("获取成功！").pagination(pagination).getMap();
		}catch (UIException e) {
			throw new UIException("获取菜单列表信息失败！");
		}
    }

    @RequestMapping("/add")
    public String add() {
    	try{
			//to-do
		}catch (UIException e) {
			throw new UIException("获取菜单信息失败！");
		}
        return "module/add";
    }

    @RequestMapping("/add/save")
    @ResponseBody
    public Map<String, Object> addSave(Module module) {
        if (module == null) {
            throw new AjaxException("保存信息不能为空！");
        }
        try{
        	moduleService.saveModule(module);
			//to-do
			Map<String, Object> rs = new HashMap<String, Object>();
			rs.put("status", HttpStatus.OK.value());
        	rs.put("message", "保存菜单成功！");
        	return rs;
		}catch (Exception e) {
			throw new AjaxException("获取菜单信息失败！");
		}
    }
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(@RequestParam(value="ids",required=false) List<String> ids){
        if (ids==null || ids.isEmpty()) {
            throw new AjaxException("错误的请求参数！");
        }
        
        Map<String, Object> rs = new HashMap<String, Object>();
        rs.put("status", HttpStatus.OK.value());
        rs.put("message", "删除菜单成功！");
        return rs;
    }
    
    @RequestMapping("/edit")
    public String edit(@RequestParam(value = "id") String id,Model model) {
        Module module = moduleService.findModuleById(id);
        if (module == null) {
            throw new UIException("未找到菜单信息！");
        }
        model.addAttribute("module", module);
        return "module/edit";
    }

    @RequestMapping("edit/save")
    @ResponseBody
    public Map<String, Object> editSave(Module module) {
        Module saveModule = moduleService.findModuleById(module.getId());
        if (saveModule == null) {
            throw new AjaxException("未找到菜单信息！");
        }
        moduleService.updateModule(saveModule);
        Map<String, Object> rs = new HashMap<String, Object>();
       	rs.put("status", HttpStatus.OK.value());
        rs.put("message", "修改菜单成功！");
        return rs;
    }
    
    /*附加的其他业务跳转*/
    /**
     * 获取bar的菜单信息
     * @param id
     * @return
     */
    @RequestMapping("find/bar")
    @ResponseBody
    public Map<String,Object> findBar(String id){
    	UserVo user = getLoginUser();
    	try {
			List<Module> ms = moduleService.findBarMenu(id, user.getId());
			return clientMap().success().message(getMessage("op.ok")).put("modules",ms).getMap();
		} catch (Exception e) {
			e.printStackTrace();
			throw new AjaxException("获取菜单信息异常！");
		}
    }
}
